class waterfall {
    constructor(el, count, gap, urls) {
        this.container = document.querySelector(el);
        //列数
        this.count = count;
        //间隙
        this.gap = gap;
        //每个图片宽度
        this.width = ((this.container.clientWidth - (this.count - 1) * this.gap)) / this.count;
        //所有图片地址
        this.urls = urls;
        //列高数组
        this.columns = new Array(this.count).fill(0);

    }
    init() {
        this.urls.forEach(src => {
            this.createImg(src)
        });

    }
    createImg(src) {
        let img = document.createElement('img');
        img.src = src;
        img.style.width = `${this.width}px`;
        img.style.position = 'absolute';
        img.onload = (e) => {
            this.setPosition(e.target)
        }
        this.container.appendChild(img)
    }
    setPosition(img) {
        //求最矮的列
        let min = Math.min(...this.columns);
        let index = this.columns.indexOf(min);
        console.log("index", index);
        img.style.left = `${index * (this.width + this.gap)}px`;
        img.style.top = `${min}px`;
        //给容器添加高度
        this.container.style.height = `${min}px`;
        //更新列的高度
        this.updateColumnHeight(index, img.clientHeight);
    }
    updateColumnHeight(index, height) {
        console.log(this.columns);
        this.columns[index] = this.columns[index] + height + this.gap;
    }
}

// const urls=[
//     '1.webp',  
//     '3.webp',
//     '4.webp',
//     '../懒加载/images/1.jpg',
//     '../懒加载/images/2.jpg',
//     '../懒加载/images/3.jpg',
//     '../懒加载/images/4.jpg',
// ]
const urls = [
    '1.webp',
    '2.jpg',
    '3.webp',
    '4.webp',
    '2.jpg',
    '3.webp',
    '4.webp',
    '1.webp',
    '2.jpg',
    '3.webp',
    '2.jpg',
    '4.webp', 
    '1.webp', 
    '3.webp',
    '2.jpg',
    '4.webp',
    '1.webp',  
    '4.webp',
    '2.jpg',
    '1.webp',  
    '3.webp',
    '2.jpg',
    '4.webp',
    '1.webp', 
    '1.webp',
    '2.jpg',
    '3.webp',
    '3.webp',
    '2.jpg',
    '4.webp',
]
const wf = new waterfall(".container", 3, 20, urls);
wf.init()